<template>
  <div class="v-editor-select">
    <!-- {{checkedFields}}{{options}} -->
    <MDropdown
      :disabled="row.readonly || isModelDisabled"
      placement="top"
    >
      <div class="g-jc-sb g-pd-l-8 g-pointer">
        <div class="g-flex-1">
          {{ selectedOption }}
        </div>
        <div
          v-if="selected && !row.readonly && !isModelDisabled"
          class="g-flex-0 g-pd-lr-4"
        >
          <img src="statics/icons/app/iconlist2.png" />
        </div>
      </div>
      <template #dropdown>
        <el-checkbox-group
          v-model="checkedFields"
          @change="handleCheckedFieldsChange"
        >
          <MDropdownMenuItem
            v-for="item in options"
            :key="item.value"
            :command="item.value"
            :closeOnClick="false"
          >
            <el-checkbox
              :key="item.value"
              :checked="checkedFields.includes(item.value)"
              :label="item.value"
            >
              {{ item.label }}
            </el-checkbox>
          </MDropdownMenuItem>
        </el-checkbox-group>
      </template>
    </MDropdown>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, Ref, inject } from "vue";
import { PropertyRow } from "../../types";
import { propertyUtil } from "../../PropertyUtil";
import MDropdown from "@/common/dropdown/Dropdown.vue";
import MDropdownMenuItem from "@/common/dropdown/DropdownMenuItem.vue";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

/**
 * 普通下拉选择，只处理固定列表的拉下选择 比如visibility（完成）
 */
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const options = computed(() => {
  return props.row.items || [];
});
const checkedFields = ref<string[]>([]);
const handleCheckedFieldsChange = () => {
  propertyUtil.updatePropertyAndFresh(props.row, checkedFields.value);
};

watch(
  () => props.row.value,
  () => {
    checkedFields.value = props.row.value as string[];
  },
  {
    immediate: true
  }
);
const selectedOption = computed(() => {
  if (props.row.items && props.row.value) {
    return options.value
      .filter(item => (props.row.value as string[]).includes(item.value))
      .map(item => item.label)
      .join(",");
  } else {
    return null;
  }
});

// function handleClickItem(item: PropertyDropdownOption) {
//   if ([PropertyKey.ItemFlow_name, PropertyKey.ItemFlow_direction].includes(props.row.key)) {
//     app.$bus.emit(BusEvent.EDITOR_CHANGE, props.row, item.value);
//     props.row.value = item.value;
//   } else {
//     // 更新属性是共性行为
//     propertyUtil.updatePropertyAndFresh(props.row, item.value);
//   }
// }
</script>
